import 'dart:async';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_getx/app/routes/app_pages.dart';
import 'package:flutter_getx/app/service/db_service.dart';
import 'package:flutter_getx/app/modules/msg_list/component/create_group.dart';
import 'package:flutter_getx/app/data/api/api.dart';
import 'package:get/get.dart';
import '../../../const.dart';
import '../../../service/local_storage_service.dart';
import '../../../service/message_service.dart';
import '../../../service/user_info_service.dart';
import '../component/add_friend_dialog.dart';


class MsgListController extends GetxController {
  DBService dbService = Get.find();
  UserInfoService userInfoService = Get.find();
  LocalStorageService localStorageService = Get.find();
  MessageService messageService = Get.find();
  Api api = new Api();

  // List chatList = [].obs;
  RxBool isAddGroup = false.obs;


  Timer? _updateTimer;

  void toChat(int idx) {
    Get.toNamed(Routes.MESSAGE, arguments: this.messageService.chatList[idx]);
  }

  @override
  Future<void> onInit() async {
    super.onInit();
  }

  Future<void> refreshChatList() async {
    // todo
    // 调用后端接口 获取有关用户列表
    await messageService.infoSync();
    var list = await api.getChatList(userInfoService.userInfo.value.id);
    // var users = await dbService.userDao.findAllUsers();
    this.messageService.chatList.clear();
    this.messageService.chatList.addAll(list);
    //
    //
    // for (int i = 0; i < users.length; i ++) {
    //   var user = users[i];
    //   userInfoService.avatarMap[user.id!] = user.avatar!;
    //   userInfoService.nicknameMap[user.id!] = user.nickname!;
    //   userInfoService.userSet.add(user.id!);
    //   this.messageService.chatList.add({
    //     'user': user.nickname,
    //     'userId': user.id,
    //     'url': user.avatar,
    //     'type': 1 //私信消息
    //   });
    // }
    //
    // var groups = await dbService.groupDao.findAllGroups();
    // for (int i = 0; i < groups.length; i ++) {
    //   var group = groups[i];
    //   this.messageService.chatList.add({
    //     'user': group.name,
    //     'userId': group.id,
    //     'url': 'https://lishuangzhi-beijing.oss-cn-beijing.aliyuncs.com/img/qun.png',
    //     'type': 2 // 群聊消息
    //   });
    // }

    // 按照时间排序
    // this.messageService.chatList.sort((a, b){
    //   if (a['time'] == null) {
    //     a['time'] = 0;
    //   }
    //   if (b['time'] == null) {
    //     b['time'] = 0;
    //   }
    //   return b['time'] - a['time'];
    // });
  }

  Future<void> check() async {
    // 没有登录情况下，没有用户id 无法连接websocket
    // var str = localStorageService.getData(localStorageService.userInfoKey);
    //
    // userInfoService.userInfo.value = UserInfo.fromJson(str);
    messageService.connect();

    await refreshChatList();
    await messageService.readFromDB();
  }

  Future<void> onMenuSelected(SelectItemAction item) async {
    switch (item) {
      case SelectItemAction.CreateGroup:
        await Get.dialog(CreateGroupDialog(), barrierDismissible: false);
        break;
      case SelectItemAction.AddGroupOrFriend:
        await Get.dialog(AddFriendDialog(), barrierDismissible: false);
        break;
    }
  }

  // 添加好友
  Future<void> add(int id) async {

    if (!isAddGroup.value) {
      // 添加好友
      bool r = await api.addFriend(userInfoService.userInfo.value.id!, id);
      if (!r) {
        return;
      } else {
        EasyLoading.showSuccess("添加成功");
      }
      // var uid = userInfoService.userInfo.value.id;
      //
      // var ufList = await api.getUserFriendEntity(uid);
      // var userList = await api.getLinkedUsers(uid);
      //
      // await dbService.userFriendDao.deleteAll();
      // await dbService.userDao.deleteAll();
      // await dbService.userFriendDao.insertUserFriends(ufList);
      // await dbService.userDao.insertUsers(userList);
    } else {
      // 加群
      bool r = await api.joinFriend(userInfoService.userInfo.value.id!, id);
      if (!r) {
        return;
      } else {
        EasyLoading.showSuccess("加群成功");
      }
    }
    this.refreshChatList();
  }

  createGroup(String groupName) async {
    bool r = await api.createGroup(userInfoService.userInfo.value.id!, groupName);
    if (r) {
      EasyLoading.showSuccess("创建成功");
      this.refreshChatList();
    }
  }

  void logout() {
    localStorageService.clearData();
    messageService.stop();
    Get.offAllNamed(Routes.LOGIN);
  }

  @override
  Future<void> onReady() async {
    await check();
    // _updateTimer = Timer.periodic(Duration(seconds: 6), (timer) {
    //   refreshChatList();
    // });
    super.onReady();
  }

  @override
  void onClose() {
    print("----close----");
    _updateTimer?.cancel();
    super.onClose();
  }
}
